import 'dart:io';

import 'package:dio/dio.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/domain/widgets/common_dialog.dart';
import 'package:flutter_syt/domain/widgets/custom_dialog.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/global_date_time_format.dart';
import 'package:flutter_syt/utils/image_picker_helper.dart';
import 'package:flutter_syt/utils/utils_other.dart';

import '../../global_easy_loading.dart';

class NucleicAcidReportPage extends StatefulWidget {
  final bool isNucleicacid;
  NucleicAcidReportPage(this.isNucleicacid);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _NucleicAcidReportState();
  }
}

class _NucleicAcidReportState extends State<NucleicAcidReportPage> {
  List<NucleicAcidReportItem> list = [];
  bool isFirst = true;
  void initState() {
    _getData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.isNucleicacid
              ? S.of(context).submit_nucleic_acid_test_result
              : S.of(context).submit_covid_19_vaccination_title),
        ),
        body: getPage());
  }

  Widget getPage() {
    if (isFirst) {
      return Container();
    } else {
      return Container(
        child: Column(
          children: [
            if (list.isEmpty) noData(),
            if (list.isNotEmpty) _list(),
            SizedBox(height: list.isEmpty == true ? 100 : 48),
            bottomActions(),
          ],
        ),
      );
    }
  }

  String _getTitle() {
    if (widget.isNucleicacid) {
      return S.of(context).un_submit_nucleic_acid;
    }
    return S.of(context).un_submit_vaccination;
  }

  Widget noData() {
    return Container(
      padding: EdgeInsets.only(top: 84),
      child: Center(
        child: Column(
          children: [
            Image.asset(
              'assets/images/nucleic_acid_empty.png',
              width: 100,
              height: 100,
            ),
            SizedBox(height: 16),
            Text(
              _getTitle(),
              style: TextStyle(
                fontWeight: FontWeight.w300,
                fontSize: 14,
                color: ThemeColor.colorBlack60,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _list() {
    var items = list.map((e) => _item(e)).toList();
    return Column(
      children: [
        Container(
          padding: EdgeInsets.fromLTRB(25, 24, 25, 6),
          child: Row(
            children: [
              Expanded(
                child: Text(
                  S.of(context).Last_three_records,
                  style: TextStyle(
                    fontWeight: FontWeight.w500,
                    fontSize: 16,
                  ),
                ),
              ),
            ],
          ),
        ),
        Container(
          child: Column(
            children: items,
          ),
        )
      ],
    );
  }

  Widget _item(NucleicAcidReportItem data) {
    var resultTxt = '';
    if (data.status == 0) {
      // 0:待审核，1审核通过，2审核拒绝
      resultTxt = S.of(context).Waiting;
    } else if (data.status == 1) {
      resultTxt = S.of(context).Approved;
    } else {
      resultTxt = S.of(context).Audit_failed;
    }
    return Container(
      padding: EdgeInsets.fromLTRB(25, 16, 25, 0),
      child: GestureDetector(
        onTap: ClickUtils.debounce(() {
          if (data.status == 2) {
            customShowToast(data.message);
            // showSingleDialog(
            //     context,
            //     DialogEntity(
            //       '',
            //       Text(
            //         data.message,
            //         textAlign: TextAlign.center,
            //       ),
            //       () {
            //         Navigator.of(context).pop();
            //       },
            //       () {
            //         Navigator.of(context).pop();
            //       },
            //       okText: '好的',
            //     )
            // );
          }
        }),
        child: Column(
          children: [
            Row(
              children: [
                Expanded(
                  child: Text(
                    data.name,
                    style: TextStyle(
                      fontWeight: FontWeight.w400,
                      fontSize: 16,
                      color: ThemeColor.colorBlack100,
                    ),
                    maxLines: 5,
                    textAlign: TextAlign.left,
                  ),
                ),
              ],
            ),
            SizedBox(height: 8),
            Row(
              children: [
                Text(
                  '${formatDate(data.createTime)}',
                  style: TextStyle(
                    color: ThemeColor.colorBlack60,
                    fontSize: 14,
                    fontWeight: FontWeight.w400,
                  ),
                ),
                Spacer(),
                Text(
                  resultTxt,
                  style: TextStyle(
                    color: ThemeColor.colorBlack40,
                    fontSize: 14,
                    fontWeight: FontWeight.w400,
                  ),
                ),
                SizedBox(width: 8),
                if (data.status == 2)
                  Image.asset('assets/icons/icon_right.png', width: 8),
              ],
            ),
            SizedBox(height: 16),
            Divider(height: 0.5),
          ],
        ),
      ),
    );
  }

  Widget bottomActions() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 24),
      child: Column(
        children: [
          Text(
            widget.isNucleicacid
                ? S.of(context).resubmitnucleic_acid_Test_result
                : S.of(context).resubmitnucleic_COVID19,
            style: TextStyle(
              fontWeight: FontWeight.w300,
              fontSize: 12,
              color: ThemeColor.colorBlack60,
            ),
          ),
          SizedBox(height: 20),
          ElevatedButton(
              child: Center(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Image.asset('assets/icons/icon_chose_img.png',
                        width: 16, height: 16),
                    SizedBox(width: 8),
                    Text(S.of(context).Select_Picture,
                        style: TextStyle(
                            fontSize: 16, fontWeight: FontWeight.bold)),
                  ],
                ),
              ),
              onPressed: ClickUtils.debounce(
                () {
                  _getMedias();
                },
              )),
          SizedBox(height: 24),
          ElevatedButton(
              child: Center(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Image.asset('assets/icons/icon_chose_file.png',
                        width: 16, height: 16),
                    SizedBox(width: 8),
                    Text(S.of(context).Select_file,
                        style: TextStyle(
                            fontSize: 16, fontWeight: FontWeight.bold)),
                  ],
                ),
              ),
              onPressed: ClickUtils.debounce(
                () {
                  _getFiles();
                },
              )),
          SizedBox(height: 24),
        ],
      ),
    );
  }

  void _getData() async {
    var res = await API.shared.epidemic
        .reportList(widget.isNucleicacid == true ? 1 : 2);
    list = res.map((e) => NucleicAcidReportItem(e)).toList();
    setState(() {
      isFirst = false;
    });
  }

  void _getFiles() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles();
    if (result != null) {
      try {
        var file = result.files.map((e) => e).first;
        var fileName = (file.path ?? "").split('/').last;
        var path = file.path ?? "";
        var res = await API.shared.common.uploadFile(fileName, path);
        _submit(res.url, fileName);
      } catch (e) {
        await UtilsOther.showCustomShowError(e);
        // if (e is DioError) {
        //   customShowToast(e.message);
        // } else {
        //   customShowToast(S().network_error);
        // }
        // print('$e');
      }
    }
  }

  void _getMedias() async {
    var result = await ImageHelper.pickSingleImage(context, source: 1);
    if (result != null) {
      var path = result.path;
      var fileName = path.split('/').last;
      var res = await API.shared.common.uploadImage(path);
      _submit(res.url, fileName);
    } else {
      customShowToast(S.of(context).img_pro_failed);
    }
  }

  void _submit(String url, String filename) async {
    try {
      await API.shared.epidemic
          .reportSubmit(widget.isNucleicacid == true ? 1 : 2, url, filename);
      _getData();
    } catch (e) {
      await UtilsOther.showCustomShowError(e);
      // if (e is DioError) {
      //   customShowToast(e.message);
      // } else {
      //   customShowToast(S.of(context).submit_failed);
      // }
    }
  }
}

class NucleicAcidReportItem {
  late String id;
  late String name;
  late String message;
  late int status; // 0:待审核，1审核通过，2审核拒绝
  late String statusName;
  late int createTime;

  NucleicAcidReportItem(Map<String, dynamic> json) {
    id = "${json["id"]}";
    name = "${json["filename"]}";
    message = "${json["message"]}";
    status = int.parse("${json["status"]}");
    statusName = "${json["status_name"]}";
    createTime = int.parse("${json["create_time"]}");
  }
}
